#!/usr/bin/env pwsh

# Redis Service Script (Start/Stop)
# Save original working directory
$OriginalDir = Get-Location

# Get command line argument, default to start mode
$mode = "start"
if ($args.Count -gt 0) {
    $mode = $args[0].ToLower()
}

if ($mode -eq "start") {
    Write-Host "Starting Redis Service..." -ForegroundColor Yellow

    # Function to check and create directory if it doesn't exist
    function Ensure-DirectoryExists {
        param (
            [string]$DirectoryPath
        )
        
        if (-not (Test-Path -Path $DirectoryPath -PathType Container)) {
            Write-Host "Creating directory: ${DirectoryPath}" -ForegroundColor Yellow
            try {
                New-Item -Path $DirectoryPath -ItemType Directory -Force | Out-Null
                Write-Host "Directory created successfully: ${DirectoryPath}" -ForegroundColor Green
            } catch {
                Write-Host "Error creating directory ${DirectoryPath}: $_" -ForegroundColor Red
                exit 1
            }
        } else {
            Write-Host "Directory already exists: ${DirectoryPath}" -ForegroundColor White
        }
    }

    # Define mount directory
    $mountDirectory = "D:/docker_data/redis/data"

    # Check and create mount directory if it doesn't exist
    Ensure-DirectoryExists -DirectoryPath $mountDirectory

    # Check and create server_network if it doesn't exist
    if (-not (docker network ls | Select-String -Pattern "server_network")) {
        Write-Host "Creating server_network network..." -ForegroundColor Yellow
        docker network create --driver bridge server_network 2>$null
    }

    # Start Redis container without rebuilding
    docker-compose -f "$PSScriptRoot\..\server\2-docker-compose-redis.yml" up -d
    Write-Host "Redis Service started successfully!" -ForegroundColor Green
    Write-Host "You can check status with: docker-compose -f .\server\2-docker-compose-redis.yml ps" -ForegroundColor White
    Write-Host "To stop the service, run: ./02manage_redis.ps1 stop" -ForegroundColor White
} elseif ($mode -eq "stop") {
    Write-Host "Stopping Redis Service..." -ForegroundColor Yellow
    # Stop Redis container using docker-compose stop
    docker-compose -f "$PSScriptRoot\..\server\2-docker-compose-redis.yml" stop
    Write-Host "Redis Service stopped successfully!" -ForegroundColor Green
    Write-Host "To start the service again, run: ./02manage_redis.ps1 start" -ForegroundColor White
} else {
    Write-Host "Invalid mode. Please use 'start' or 'stop'." -ForegroundColor Red
    Write-Host "Example: ./02manage_redis.ps1 start" -ForegroundColor White
    Write-Host "Example: ./02manage_redis.ps1 stop" -ForegroundColor White
    exit 1
}

# Return to original working directory
Set-Location $OriginalDir
Write-Host "Returned to original directory: $OriginalDir" -ForegroundColor White